<template>
    <div class="app-container">
      <el-row>
        <el-col :span="4" :xs="24">
          <div class="left-container">
            <el-input
              v-model="queryParams.templateName"
              placeholder="请输入模板名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="left-container" >
            <el-tree
              :data="eltreeData"
              :check-strictly="false"
              node-key="id"
              default-expand-all
              highlight-current
              @node-click="handleNodeClick"
            >
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ data.label }}</span>
                <span>
                  <el-button
                    type="text"
                    size="mini"
                    v-if="(data.children != null && data.children.length >= 0 && data.templateId == null)"
                    @click.stop="() => append(data)">
                    添加
                  </el-button>
                  <el-button
                    type="text"
                    size="mini"
                    v-if="(data.children == null || data.children.length == 0) && data.templateId != null"
                    @click.stop="() => remove(node, data)">
                    删除
                  </el-button>
                </span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="6" :xs="24" style="margin-left: 20%">
          <div class="right--container">
            <el-card class="box-card" style="width: 140%;">
              <div slot="header" class="clearfix">
                <span>模板编辑</span>
              </div>
              <el-form label-width="100px">
                <el-form-item label="模板名称">
                  <el-input type="text" v-model="param.templateName" style="width: 90%; padding-left: 10%;"></el-input>
                </el-form-item>
                <el-form-item label="参数类型">
                  <el-select @change="addInput" multiple v-model="param.paramIdList" style="width: 90%; padding-left: 10%;">
                    <el-option-group
                      v-for="group in devParamList"
                      :key="group.label"
                      :label="group.label"
                    >
                      <el-option
                        v-for="item in group.options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value"
                      >
                      </el-option>
                    </el-option-group>
                  </el-select>
                </el-form-item>
                <el-form-item
                  v-for="item in inputList"
                  :key="item.name"
                  :label="item.name + '(' + item.unit + ')'"
                >
                  <el-input style="width: 90%; padding-left: 10%;" type="text" v-model="item.threshold"></el-input>
                </el-form-item>
              </el-form>
              <div style="width: 40%; margin-left: 64%">
                <el-button @click="handleCancel()">取消</el-button>
                <el-button type="primary" @click="handleSubmit()">提交</el-button>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>
    </div>
</template>
<script>
import {getMonitorTemplateNameList, addMonitorParamsTemplates, getTemplateInfoById, delMonitorParamsTemplatesById, editMonitorParamsTemplates} from "../../../../api/alm/dev-exception/dev-ex-template"
import {getDevMonitorParams} from "@/api/alm/dev-base-info/dev-base-info-manage/dev-base-info-manage";
export default {
  data() {
    return {
      name: "Index",
      queryParams: {
        templateName: '',
      },
      param: {
        id: -1,
        templateName: '',
        paramIdList: [],
        userInputValueList: [],
      },
      devParamMap: {},
      devParamList: [],
      inputList: [],
      templateList: [
        
      ],
      eltreeData:  [],
    }
  },
  mounted() {
    this.loadDevMonitorParams()
    this.getMonitorTemplateNameList()
  },
  methods: {
    getMonitorTemplateNameList() {
      let _this = this
      let obj = _this.queryParams
      console.log(_this.queryParams)
      getMonitorTemplateNameList(obj).then(res => {
        // console.log(res.data)
        let children = new Array();
        res.data.almMonitorTemplateVOList.forEach(function(item) {
          let obj = {}
          obj.label = item.templateName
          obj.templateId = item.id
          children.push(obj)
        })
        // console.log(children)
        let obj = {}
        obj.label = res.data.userName;
        obj.children = children
        _this.eltreeData.push(obj)

      })
    },
    loadDevMonitorParams() {
      // 设置查询设备参数类型为1
      let obj = {}
      obj.paramType = 1

      getDevMonitorParams(obj).then((response) => {
        this.devParamMap = response.data;
        this.devParamList = [];

        for (let key in this.devParamMap) {
          if (this.devParamMap.hasOwnProperty(key)) {
            let arr = this.devParamMap[key];

            let paramObj = {
              label: key,
              options: [],
            };
            arr.forEach((item) => {
              paramObj.options.push({
                value: item.id,
                label: item.name,
              });
            });
            this.devParamList.push(paramObj);
          }
        }
      });
    },
    getTemplateInfoById(templateId) {
      getTemplateInfoById(templateId).then(res => {
        console.log(res)
        this.param.id = res.data.id
        this.param.templateName = res.data.templateName
        this.param.paramIdList = []
        for (let i = res.data.userInputValueList.length - 1; i >= 0; i--) {
          this.param.paramIdList.push(res.data.userInputValueList[i].code)
        }
        this.addInput()
        // console.log(this.inputList)
        for (let i = 0; i < this.inputList.length; i++) {
          this.inputList[i].threshold = res.data.userInputValueList[i].threshold
        }
      })
    },
    append(data) {
      const newChild = { label: '自定义模板', templateId: -1, children: [] };
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      data.children.push(newChild);
    },
    remove(node, data) {
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.label === data.label);
        children.splice(index, 1);
        console.log(node.data.templateId)
        delMonitorParamsTemplatesById(node.data.templateId).then(res => {
          this.$message.success("删除成功！")
        })
      },
    addInput() {
      this.inputList = [];
      for (let key in this.devParamMap) {
        if (this.devParamMap.hasOwnProperty(key)) {
          let objArr = this.devParamMap[key];
          objArr.forEach((item) => {
            this.param.paramIdList.forEach((item2) => {
              if (item.id === item2) {
                this.inputList.push(item);
              }
            });
          });
        }
      }
    },
    handleNodeClick(node) {
      // console.log(node)
      if(node.templateId === -1) {
        this.param.id = node.templateId
        this.param.templateName = node.label
        this.param.paramIdList = []
        this.inputList = []
      } else if(node.templateId != null){
        this.getTemplateInfoById(node.templateId)
      }
    },
    handleCancel() {
      this.param.templateName = ''
      this.param.paramIdList = []
      this.inputList = []
    },
    handleSubmit() {
      this.param.userInputValueList = this.inputList
      // console.log(this.param.id)
      if(this.param.id == -1) {
        addMonitorParamsTemplates(this.param).then(res => {
          if(res.code === 200) {
            this.$message.success(res.msg)
            this.eltreeData = []
            this.getMonitorTemplateNameList()
          }
        })
      }
      else {
        editMonitorParamsTemplates(this.param).then(res => {
          console.log(res)
          if(res.code === 200) {
            this.$message.success(res.msg)
            this.eltreeData = []
            this.getMonitorTemplateNameList()
          }
        })
      }
    }
  },
}
</script>
<style scoped>
  .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
    } 
</style>